<?php
defined('IN_TS') or die('Access Denied.');
class yidi extends tsApp{
	public $yidi_url = 'https://yidivip.com/api/v2'; 
	protected $tsMySqlCache;

	//构造函数
	public function __construct($db){
        $tsAppDb = array();


		//判断APP是否采用独立数据库
		if($tsAppDb){
			$db = new MySql($tsAppDb);
		}
	
		parent::__construct($db);
		
	}
	
	/**
	 * 获取益迪云图登陆token
	 *
	 * @return void
	 */
	public function getYidiToken()	
	{
		global $YD;
		global $tsMySqlCache;

		$token = $tsMySqlCache->get("yidi_token");	
		if ($token) return $token;

		try {
			$data = $YD;
			$url = "{$this->yidi_url}/account/login/admin";
			$res = vpost($url, json_encode($data), 1);		
			$result = json_decode($res, true);
			$token = $result["data"]["token"];
			$tsMySqlCache->set("yidi_token", $token, 1500);
		} catch (\Throwable $th) {
			json_response(0, $th->getMessage());	
		}
		return $token;
	}
	
	public function getAuthorization()
	{
		$token = $this->getYidiToken();
		$authorization = "Bearer {$token}";
		return $authorization;
	}
	
	/**
	 * 分馆列表
	 *
	 * @param integer $group
	 * @return array
	 */
	public function libList($group = 13)
	{
		$url = "{$this->yidi_url}/library/group/{$group}";
		$res = vget($url, $this->getAuthorization());	
		return json_decode($res, true);
	}
	
	/**
	 * 数据总览
	 *
	 * @return array
	 */
	public function overview($libraryid = '')	
	{
		$url = "{$this->yidi_url}/statics/basic?libraryid={$libraryid}";
		$res = vget($url, $this->getAuthorization());	
		return json_decode($res, true);
	}
	

	/**
	 * 读者和书籍排行榜
	 *
	 * @param integer $library_id
	 * @param string $date_start
	 * @param string $date_end
	 * @return array
	 */
	public function rankingList($libraryid = '', $date_start = null, $date_end = null)
	{
		if (!$date_start) $date_start = date('Y/m/1');
		if (!$date_end) $date_end = date('Y/m/t');
		$url = "{$this->yidi_url}/statics/rank_range?libraryid={$libraryid}"
			."&start={$date_start}&end={$date_end}";
		$res = vget($url, $this->getAuthorization());	
		return json_decode($res, true);
	}
}